package com.common.utils
{
	import flash.events.*;
	import flash.utils.*;
	/**
	 *时间驱动 
	 * @author lxh
	 * 
	 */	
	public class TimeFrameUtil 
	{
		private static var _instance:TimeFrameUtil;
		
		private var _passTime:int;
		private var _tempT:int;
		private var _timer:Timer;
		private var _methodDic :Vector.<Function>;
		
		public function TimeFrameUtil()
		{
			_methodDic = new Vector.<Function>;
			_timer = new Timer(20);
			_timer.addEventListener(TimerEvent.TIMER, onTime);
			_tempT = getTimer();
			_timer.start();
		}
		public static function get instance():TimeFrameUtil
		{
			if(_instance == null)
			{
				_instance = new TimeFrameUtil();
			}
			return _instance;
		}
		/**
		 *添加方法 
		 * @param func
		 * 
		 */		
		public function addMethod(func:Function):void
		{
			var fc:Function;
			for each (fc in _methodDic) 
			{
				if (fc == func)
				{
					return;
				}
			}
			_methodDic.push(func);
		}
		/**
		 * 添加方法 
		 * @param func
		 * @param index
		 * 
		 */		
		public function addMethodAt(func:Function, index:int):void
		{
			var fc:Function;
			for each (fc in _methodDic) 
			{
				if (fc == func)
				{
					return;
				}
			}
			_methodDic.splice(index, 0, func);
		}
		/**
		 *删除方法  
		 * @param func
		 * 
		 */		
		public function removeMethod(func:Function):void
		{
			var fc:Function;
			var i:int;
			for each (fc in _methodDic)
			{
				if (fc == func)
				{
					_methodDic.splice(i, 1);
					return;
				}
				i++;
			}
		}
		
		public function get length():int
		{
			return _methodDic.length;
		}
		/**
		 *更新  
		 * @param e
		 * 
		 */		
		private function onTime(e:TimerEvent):void
		{
			var fc:Function;
			_passTime = (getTimer() - _tempT);
			_tempT = getTimer();
			for each (fc in _methodDic) 
			{
				fc(_passTime);
			}
			e.updateAfterEvent();
		}
	}
}